package com.kfm.base.anno;

import com.kfm.base.reflect.DBHelper;
import com.kfm.base.reflect.Dept;
import com.kfm.base.reflect.Emp;
import com.kfm.base.reflect.User;

import java.lang.reflect.*;
import java.util.List;

public class Test02 {

    public static void main(String[] args) {

        // 代理模式
        DeptDAO deptDAO = getDeptDAO();

        List<Dept> depts = deptDAO.selectAll();

        List<User> users = deptDAO.selectAllUser();

        List<Emp> emps = deptDAO.selectAllEmp();

        System.out.println(emps);
    }

    public static DeptDAO getDeptDAO(){
        DBHelper dbHelper = new DBHelper("jdbc:mysql://localhost:3306/company", "root", "");
        DeptDAO deptDAO = (DeptDAO) Proxy.newProxyInstance(Test02.class.getClassLoader(),
                new Class[]{DeptDAO.class}, new InvocationHandler() {
                    @Override
                    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                        System.out.println(method);
                        Select annotation = method.getAnnotation(Select.class);
                        if (annotation != null){
                            String sql = annotation.sql();

                            Class<?> returnType = method.getReturnType();
                            if (returnType == List.class){
                                System.out.println("多条数据");
                                ParameterizedType genericReturnType = (ParameterizedType) method.getGenericReturnType();
                                // 获取泛型类型
                                Type actualTypeArgument = genericReturnType.getActualTypeArguments()[0];
//                                System.out.println(actualTypeArgument.getTypeName());

                                List<?> objects = dbHelper.selectList(sql, Class.forName(actualTypeArgument.getTypeName()));

                                return objects;

                            } else {

                            }
                        }
                        return null;
                    }
                });
        return deptDAO;
    }
}
